// 后端传过来的商品信息
var product = {
    "product": {
        "id": 17,
        "categoryId": 8,
        "providerId": 16,
        "name": "欧迪惠  新款连衣裙22年女装套装夏季韩版大码牛仔裙休闲时尚气质短袖印花衣服夏天两件套套装裙子女夏 白T+浅色 M",
        "stock": 299,
        "price": 132,
        "img": "https://img10.360buyimg.com/n1/jfs/t1/35147/37/16024/186928/60f165f7E44010b79/a9edb61f04498283.jpg",
        "detail": "欧迪惠新款连衣裙22年...店铺:欧迪惠旗舰店商品毛重:400.00g商品产地:中国大陆货号:ODH JD521X69材质:棉49%衣门襟:套头袖长:短袖裙长:中长裙腰型:高腰适用年龄:18-24周岁，25-29周岁领型:圆领裙型:A字裙流行元素:纽扣，口袋袖型:常规袖风格:百搭上市时间:2022年夏季图案:动物，字母，卡通动漫廓形:A型",
        "createTime": "2022-03-18T08:08:08.000+00:00",
        "status": null,
        "category": {
            "id": 8,
            "name": "服装类",
            "sum": null
        },
        "provider": {
            "id": 16,
            "code": "oudihui",
            "name": "欧迪惠旗舰店",
            "detail": "女性衣物",
            "contact": "京东",
            "tel": "13847569847",
            "address": "浙江省",
            "img": null,
            "status": null,
            "createTime": null
        }
    },
    "provider": null,
    "sames": [
        {
            "id": 17,
            "categoryId": 8,
            "providerId": 16,
            "name": "欧迪惠  新款连衣裙22年女装套装夏季韩版大码牛仔裙休闲时尚气质短袖印花衣服夏天两件套套装裙子女夏 白T+浅色 M",
            "stock": 299,
            "price": 132,
            "img": "https://img10.360buyimg.com/n1/jfs/t1/35147/37/16024/186928/60f165f7E44010b79/a9edb61f04498283.jpg",
            "detail": "欧迪惠新款连衣裙22年...店铺:欧迪惠旗舰店商品毛重:400.00g商品产地:中国大陆货号:ODH JD521X69材质:棉49%衣门襟:套头袖长:短袖裙长:中长裙腰型:高腰适用年龄:18-24周岁，25-29周岁领型:圆领裙型:A字裙流行元素:纽扣，口袋袖型:常规袖风格:百搭上市时间:2022年夏季图案:动物，字母，卡通动漫廓形:A型",
            "createTime": "2022-03-18T08:08:08.000+00:00",
            "status": null,
            "category": null,
            "provider": null
        }
    ]
}
var recommend = [
    {
        "neoProduct": {
            "id": 16,
            "productName": "勇气系列限定套装 被讨厌的勇气 幸福的勇气 勇气日历套装 2本图书+1本日历"
        },
        "img": "https://img14.360buyimg.com/n1/jfs/t1/144469/30/20960/120951/619dce65Eac8151d0/34567bea5d2a7930.jpg",
        "price": 99,
        "count": 58
    },
    {
        "neoProduct": {
            "id": 17,
            "productName": "欧迪惠  新款连衣裙22年女装套装夏季韩版大码牛仔裙休闲时尚气质短袖印花衣服夏天两件套套装裙子女夏 白T+浅色 M"
        },
        "img": "https://img10.360buyimg.com/n1/jfs/t1/35147/37/16024/186928/60f165f7E44010b79/a9edb61f04498283.jpg",
        "price": 132,
        "count": 57
    },
    {
        "neoProduct": {
            "id": 12,
            "productName": "好乐果 8个装海南金都一号国产红心火龙果 蜜宝 红肉火龙果生鲜 单果300-200g"
        },
        "img": "https://img10.360buyimg.com/n1/jfs/t1/150327/30/19484/125818/5fe209e8Eb1cad84b/0fd3b7787fb7b714.jpg",
        "price": 36.8,
        "count": 54
    }
]
$render_product = $('#product-detail-render-entry')
$render_provider = $('#product-detail-provider-entry')
function load(delay){
    setTimeout(()=>{
        $('.placeholder').removeClass('placeholder')
    }, delay)
}
function load_wave(delay){
    setTimeout(()=>{
        $('.placeholder-wave').removeClass('placeholder-wave')
    }, delay)
}
///////////////// 获取信息
function ajaxGetProductWithTypeAndProviderById(){
    let productId = paramGetURL(location.href, 'productId')
    $.ajax({
        url: '/product/query/' + productId,
        type: 'POST',
        async: false,
        dataType: 'json',
        error: (err) =>{
            ms_show_toast(false, err.responseText)
            console.error(err.responseText)
        },
        success: (result) =>{
            if(result['code'] === CODE_SUCCESS)
                product = result['data']
            else
                ms_show_toast(false, '未获取到商品ID为: [' + id + '] 的信息')
        }
    })
    console.log(product)
}

///////////////// 渲染商品的详细信息
function renderProductDetail(product){
    // 处理一下空的商品描述
    if (product['detail'] === '')
        product['detail'] = '暂无'
    $render_product.html('')
    $render_product.html(`
       <div class="card-body">
            <h5 class="card-title display-6 placeholder bg-light">${product['name']}</h5>
            <p class="card-text fs-6 placeholder" >商品分类：${product['category']['name']}</p>
            <p class="card-text fs-6 placeholder">商品价格：<span class="text-danger">￥${product['price']}</span></p>
            <p class="card-text fs-6 placeholder">商品描述：${product['detail']}</p>
            <p class="card-text fs-6 placeholder">库存：<span id="product-detail-stock">${product['stock']}</span> 件</p>
            <button id="detail-btn-reduce" class="btn btn-light placeholder">-</button>
            <input alt="购买数量" id="detail-input-stock" name="stock" size="6" width="6px" value="1">
            <button id="detail-btn-add" class="btn btn-light">+</button>
            <a onclick="ms_show_toast(true, '该功能暂未开发')" class="btn btn-warning placeholder">
                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-cart-plus" viewBox="0 0 16 16">
                    <path d="M9 5.5a.5.5 0 0 0-1 0V7H6.5a.5.5 0 0 0 0 1H8v1.5a.5.5 0 0 0 1 0V8h1.5a.5.5 0 0 0 0-1H9V5.5z"/>
                    <path d="M.5 1a.5.5 0 0 0 0 1h1.11l.401 1.607 1.498 7.985A.5.5 0 0 0 4 12h1a2 2 0 1 0 0 4 2 2 0 0 0 0-4h7a2 2 0 1 0 0 4 2 2 0 0 0 0-4h1a.5.5 0 0 0 .491-.408l1.5-8A.5.5 0 0 0 14.5 3H2.89l-.405-1.621A.5.5 0 0 0 2 1H.5zm3.915 10L3.102 4h10.796l-1.313 7h-8.17zM6 14a1 1 0 1 1-2 0 1 1 0 0 1 2 0zm7 0a1 1 0 1 1-2 0 1 1 0 0 1 2 0z"/>
                </svg>
                加入购物车
            </a>
            <a class="btn btn-primary placeholder" data-bs-toggle="modal" href="#exampleModalToggle" role="button">
                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-hand-index" viewBox="0 0 16 16">
                    <path d="M6.75 1a.75.75 0 0 1 .75.75V8a.5.5 0 0 0 1 0V5.467l.086-.004c.317-.012.637-.008.816.027.134.027.294.096.448.182.077.042.15.147.15.314V8a.5.5 0 1 0 1 0V6.435a4.9 4.9 0 0 1 .106-.01c.316-.024.584-.01.708.04.118.046.3.207.486.43.081.096.15.19.2.259V8.5a.5.5 0 0 0 1 0v-1h.342a1 1 0 0 1 .995 1.1l-.271 2.715a2.5 2.5 0 0 1-.317.991l-1.395 2.442a.5.5 0 0 1-.434.252H6.035a.5.5 0 0 1-.416-.223l-1.433-2.15a1.5 1.5 0 0 1-.243-.666l-.345-3.105a.5.5 0 0 1 .399-.546L5 8.11V9a.5.5 0 0 0 1 0V1.75A.75.75 0 0 1 6.75 1zM8.5 4.466V1.75a1.75 1.75 0 1 0-3.5 0v5.34l-1.2.24a1.5 1.5 0 0 0-1.196 1.636l.345 3.106a2.5 2.5 0 0 0 .405 1.11l1.433 2.15A1.5 1.5 0 0 0 6.035 16h6.385a1.5 1.5 0 0 0 1.302-.756l1.395-2.441a3.5 3.5 0 0 0 .444-1.389l.271-2.715a2 2 0 0 0-1.99-2.199h-.581a5.114 5.114 0 0 0-.195-.248c-.191-.229-.51-.568-.88-.716-.364-.146-.846-.132-1.158-.108l-.132.012a1.26 1.26 0 0 0-.56-.642 2.632 2.632 0 0 0-.738-.288c-.31-.062-.739-.058-1.05-.046l-.048.002zm2.094 2.025z"/>
                </svg>
                立即购买
            </a>
        </div>
    `)
    let $input = $('#detail-input-stock')
    $('#detail-btn-reduce').click(function (){
        let newVal = $input.val()
        newVal = Math.max(1, parseInt(newVal) - 1)
        if(newVal == null || isNaN(newVal))
            newVal = 1
        $input.val(newVal)
    })
    $('#detail-btn-add').click(function (){
        let newVal = $input.val()
        newVal = Math.min($('#product-detail-stock').text(), parseInt(newVal) + 1)
        if(newVal == null || isNaN(newVal))
            newVal = 1
        $input.val(newVal)
    })
    // 渲染商品图片
    $('#product-detail-product-img').attr('src', product['img'])
                                    .addClass('placeholder-wave')
    load(DELAY_PRODUCT_APPEARED)
    load_wave(DELAY_PRODUCT_APPEARED_WAVE)
}

//////////////// 渲染当前供应商的详细信息
function renderProviderDetail(provider){
    $render_provider.html('')
    $render_provider.html(`
         <div class="card-body">
            <h5 class="card-title fs-6">店铺信息: <span class="fw-bold">${provider['name']}</span></h5>
            <p class="card-text fs-6" >
            发货地: 
            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-geo-alt" viewBox="0 0 16 16">
              <path d="M12.166 8.94c-.524 1.062-1.234 2.12-1.96 3.07A31.493 31.493 0 0 1 8 14.58a31.481 31.481 0 0 1-2.206-2.57c-.726-.95-1.436-2.008-1.96-3.07C3.304 7.867 3 6.862 3 6a5 5 0 0 1 10 0c0 .862-.305 1.867-.834 2.94zM8 16s6-5.686 6-10A6 6 0 0 0 2 6c0 4.314 6 10 6 10z"/>
              <path d="M8 8a2 2 0 1 1 0-4 2 2 0 0 1 0 4zm0 1a3 3 0 1 0 0-6 3 3 0 0 0 0 6z"/>
            </svg>
            ${provider['address']}
            </p>
            <p class="card-text fs-6" >店铺详情: ${provider['detail']}</p>
            <a href="#" class="btn btn-light">
                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-chat-dots" viewBox="0 0 16 16">
                    <path d="M5 8a1 1 0 1 1-2 0 1 1 0 0 1 2 0zm4 0a1 1 0 1 1-2 0 1 1 0 0 1 2 0zm3 1a1 1 0 1 0 0-2 1 1 0 0 0 0 2z"/>
                    <path d="m2.165 15.803.02-.004c1.83-.363 2.948-.842 3.468-1.105A9.06 9.06 0 0 0 8 15c4.418 0 8-3.134 8-7s-3.582-7-8-7-8 3.134-8 7c0 1.76.743 3.37 1.97 4.6a10.437 10.437 0 0 1-.524 2.318l-.003.011a10.722 10.722 0 0 1-.244.637c-.079.186.074.394.273.362a21.673 21.673 0 0 0 .693-.125zm.8-3.108a1 1 0 0 0-.287-.801C1.618 10.83 1 9.468 1 8c0-3.192 3.004-6 7-6s7 2.808 7 6c0 3.193-3.004 6-7 6a8.06 8.06 0 0 1-2.088-.272 1 1 0 0 0-.711.074c-.387.196-1.24.57-2.634.893a10.97 10.97 0 0 0 .398-2z"/>
                </svg>
                联系卖家
            </a>
        </div>
    `)
}
/////////////// 渲染同款商品
function renderSameProduct(products){
    let $entry = $('#product-detail-same-entry')
    $entry.html('')
    first = true
    products.forEach(function (p){
        $entry.append(`
            <div class="carousel-item ${first === true ? 'active' : ''}">
                <a href="${paramUpdateCurrentParam('productId', p.id)}"><img src="${p.img}" class="d-block" alt="..." style="width: 300px;height: 300px;"> </a>            
            </div>
        `)
        first = false
    })
    $entry.parent().prepend(`
       <button class="carousel-control-prev" type="button" data-bs-target="#product-carousel" data-bs-slide="prev">
            <span class="carousel-control-prev-icon" aria-hidden="true"></span>
            <span class="visually-hidden">上一个推荐</span>
        </button>
        <button class="carousel-control-next" type="button" data-bs-target="#product-carousel" data-bs-slide="next">
            <span class="carousel-control-next-icon" aria-hidden="true"></span>
            <span class="visually-hidden">下一个推荐</span>
        </button>
    `)
}
///////////////////////////////// 功能函数区
// 确认购买
function addOrder(btn){
    ms_show_toast(true, '您已成功下单，接下来可以结算!')
    let number = eval($('#detail-input-stock').val())
    let price = product['product']['price']
    let result = ajaxByJSON(
        {
            'url': '/order/insert',
            'type': 'POST',
            'data': JSON.stringify(
                {
                    'productId': product['product']['id'],
                    'providerId': product['provider']['id'],
                    'number': number,
                    'price': number * price
                })
        })
    // 渲染页面
    renderModal(btn, result['data'])
    $('#modal-order-product-name').val(product['product']['name'])
    // 价格特殊处理，需保留两位小数
    $('#show-price').val(product['product']['price'].toFixed(2))
    $('#modal-order-time').val(dateFormat('YYYY 年 mm 月 dd 日 HH:MM:SS', new Date(result['data']['createTime'])))
}
// 结算订单
function payOrder(orderInput){
    let result = ajaxCustom('POST', {url: '/order/update/pay/' + $(orderInput).val()})
    if(result['code'] === CODE_SUCCESS){
        ms_show_toast_callback(true, result['msg'], function (){
            location.href = '/user-center.html?type=order'
        })
    } else
        ms_show_toast(false, result['msg'])
}
$(document).ready(function (){
    // 加载弹窗
    // 初始化插件
    ajaxGetProductWithTypeAndProviderById()
    renderProductDetail(product['product'])
    renderProviderDetail(product['provider'])
    renderSameProduct(product['sames'])
})
